<template>
	<view class="xbc-editor">
		<!--输入区-->
		<view class="top flex-row">
			<view @tap="triggerAudio" class="icon flex-column">
				<text v-show="oper != 'audio'" class="iconfont icon-audio"></text>
				<text v-show="oper == 'audio'" class="iconfont icon-keyboard"></text>
			</view>
			<view class="block">
				<textarea
					@focus="onFocus"
					@blur="isFocus=false"
					v-model="content"
					class="textarea"
					:show-confirm-bar="false"
					:disabled="oper == 'audio'"
					:cursor-spacing="24"
					:maxlength="10000"
					:auto-blur="false"
					auto-height
					fixed />
				<EditorAudio @success="audioRecordSuccess" v-if="oper == 'audio'" />
			</view>
			<view class="button flex-row">
				<view @tap="trigger('emoji')" class="icon flex-column">
					<text class="iconfont icon-emoji"></text>
				</view>
				<view @tap="trigger('more')" v-show="!content" class="icon flex-column">
					<text class="iconfont icon-plus-circle"></text>
				</view>
				<view @tap="sendTextMessage" v-show="content" class="send flex-column">发送</view>
			</view>
		</view>
		<!--表情-->
		<EditorEmoji @select="selectEmoji" v-show="oper == 'emoji'" :show="!isFocus" />
		<!--更多-->
		<EditorMore @success="uploadSuccess" v-show="oper == 'more'" :show="!isFocus" />
	</view>
</template>

<script>
import XBCIM from 'xbcim'
import EditorMore from './components/more.vue'
import EditorAudio from './components/audio/index.vue'
import EditorEmoji from './components/emoji/index.vue'
import { useEditor } from '@/hooks/useEditor'
const { scrollToBottom } = useEditor()
export default{
	components: { EditorMore, EditorAudio, EditorEmoji },
	data(){
		return {
			oper: 'input',	// 当前操作：input-输入，audio-录音，emoji-表情，more-更多
			content: '',
			isFocus: false,
			quoteMessage: null,
			mentionMembers: [],
			placeholderHeight: '61px'
		}
	},
	onLoad(){
		this.$emit('change', this.placeholderHeight)
	},
	methods: {
		// 发送文本消息
		sendTextMessage() {
		  try {
		    // 组合文本消息体
		    const { targetId, type } = uni.getStorageSync('currentConversation')
		    const message = XBCIM.createTextMessage({
				id: new Date().getTime(),
				target: targetId,
				content: this.content,
				conversationType: type,
				quote: this.quoteMessage,
				at: this.mentionMembers
			})
			
			// 组合前端显示消息
			const { user } = XBCIM.getAppData()
			this.$emit('send', {
				...message,
				content: JSON.stringify(message.content),
				senderId: user.userId,
				senderName: user.name,
				senderAvatar: user.avatar
			})
			
			// 发送消息
			this.sendMessage(message)
		  } catch (error) {
		    console.error(error)
		  }
		},
		// 发送消息
		sendMessage(message) {
		  XBCIM.sendMessage(message).then(() => {}).catch(error => {
			  uni.showToast({
			  	icon: 'none',
				title: error.msg
			  })
		  })
		  this.content = ''
		  this.quoteMessage = null
		  this.mentionMembers = []
		},
		// 切换
		trigger(op) {
			setTimeout(() => {
				this.oper = op
				this.getFootHeight(this.placeholderHeight)
			}, 100)
		},
		// 上传成功
		uploadSuccess({ type, data }) {
			let message
			const id = new Date().getTime()
			const { targetId, type: conversationType } = uni.getStorageSync('currentConversation')
			
			switch (type){
				case 'file':
					message = XBCIM.createFileMessage({
						id,
						quote: JSON.parse(this.quoteMessage),
						at: this.mentionMembers,
						conversationType,
						target: targetId,
						name: '这是一个测试文档',
						size: 227161,
						url: data.url,
					})
					break
				case 'image':
					message = XBCIM.createImageMessage({
						id,
						quote: JSON.parse(this.quoteMessage),
						at: this.mentionMembers,
						conversationType,
						target: targetId,
						url: data.url,
					})
					break
				case 'video':
					message = XBCIM.createVideoMessage({
						id,
						quote: JSON.parse(this.quoteMessage),
						at: this.mentionMembers,
						conversationType,
						coverUrl: 'https://cdn.xiangbaicheng.com/public/media/mov.jpg',
						duration: '00:00:10.03',
						target: targetId,
						size: 788493,
						width: 320,
						height: 176,
						url: data.url,
					})
					break
				case 'location':
					message = XBCIM.createLocationMessage({
						id,
						quote: JSON.parse(this.quoteMessage),
						at: this.mentionMembers,
						conversationType,
						target: targetId,
						name: data.name,
						address: data.address,
						latitude: data.latitude,
						longitude: data.longitude,
					})
					break
				case 'card':
					message = XBCIM.createCardMessage({
						id,
						quote: JSON.parse(this.quoteMessage),
						at: this.mentionMembers,
						conversationType,
						target: targetId,
						...data
					})
					break
			}
			
			this.sendMessage(message)
			this.reset()
		},
		// 音频录制成功
		audioRecordSuccess({ duration, url }) {
			const { targetId, type } = uni.getStorageSync('currentConversation')
			const message = XBCIM.createAudioMessage({
				id: new Date().getTime(),
				quote: JSON.parse(this.quoteMessage),
				at: this.mentionMembers,
				conversationType: type,
				target: targetId,
				duration,
				url
			})
			this.sendMessage(message)
		},
		// 切换语音
		triggerAudio() {
			this.oper = this.oper == 'audio' ? 'input' : 'audio'
			this.getFootHeight(this.placeholderHeight)
		},
		// 选择表情
		selectEmoji(emoji) {
			this.content += emoji
		},
		// 就聚焦
		onFocus() {
			this.isFocus = true
			this.oper = 'input'
		},
		// 重置
		reset(isBottom = true) {
			if(this.oper != 'audio'){
				this.oper = 'input'
				this.getFootHeight(this.placeholderHeight, isBottom)
			}
		},
		// 获取底部高度
		async getFootHeight(placeholderHeight, isBottom=true) {
			await new Promise(resolve => setTimeout(resolve, 200))
			
			let query = uni.createSelectorQuery().in(this)
			const rect = await new Promise((resolve) => {
				query.select('.xbc-editor').boundingClientRect(resolve).exec()
			})
			this.placeholderHeight = `${rect?.height}px`
			this.$emit('change', this.placeholderHeight)
			isBottom && await scrollToBottom()
		}
	}
}
</script>

<style lang="scss" scoped>
.xbc-editor {
	width: 100%;
	background-color: #f5f5f5;
	border-top: 2rpx solid #eee;
	transition: height 0.3s ease;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 999;
	
	::-webkit-scrollbar {
		display: none;
	}
	
	.top {
		padding: 20rpx 10rpx;
		align-items: flex-end;
		
		.send {
			color: #fff;
			width: 100rpx;
			height: 64rpx;
			margin: 0 10rpx;
			font-size: 28rpx;
			border-radius: 10rpx;
			background-color: #2BA245;
		}
		
		.block {
			flex: 1;
			margin: 0 10rpx;
			padding: 0 20rpx;
			overflow: hidden;
			min-height: 76rpx;
			border-radius: 10rpx;
			background-color: #fff;
			position: relative;
		}
		
		.textarea {
			width: 100%;
			color: #333;
			font-size: 30rpx;
			max-height: 160px;
			padding-top: 20rpx;
			padding-bottom: 12rpx;
			background-color: #fff;
		}
		
		.icon {
			@include fullsize(80rpx);
			
			.iconfont {
				font-size: 60rpx;
				
				&.icon-emoji {
					font-size: 58rpx;
				}
			}
		}
	}
}

</style>